<template>
  <view class="group-home">
    <customHeader
      title="邀好友，组团学"
      :scrollTop="scrollTop"
      :beforeLeaveFn="handleBeforeLeave"
    />
    <scroll-view
      :scroll-y="true"
      :enable-back-to-top="true"
      :scroll-with-animation="true"
      class="group-home-main"
      @scroll="handleScroll"
    >
      <view class="main-title" :style="groupStyleBg">
        <view class="group-rule" @tap="handleShowRuleModal">
          <text>组团规则</text>
          <image class="group-rule-img" :src="GROUP_RULE" />
        </view>
        <!-- 组团头部排行 -->
        <groupTips
          v-if="isShowHeadRank"
          :activity_data="activity_data"
          @to-rank="handleLookRank"
        />
      </view>
      <view class="group-home-content" :style="groupHomeContentStyle">
        <!-- 团成员信息 -->
        <clockContent
          v-if="isshowMemberInfo"
          :class="{ 'has-operation': isNotFormGroup }"
          :is-remove-status="isRemoveStatus"
          :group-info="groupInfo"
          :not-form-group="isNotFormGroup"
          :activity_data="activity_data"
          :isShowEditButton="isShowEditButton"
          @edit="handleEditGroupName"
          @remove="handleRemoveMember"
          @punch-operat="handlePunchOperate"
        />
        <!-- 操作团成员 -->
        <operationMember
          v-if="isNotFormGroup && !isShowActivityOver"
          :group-info="groupInfo"
          :is-remove-status="isRemoveStatus"
          :hasMember="hasGroupMember"
          @operate="handleOperate"
        />
        <!-- 立即入团 -->
        <groupGuide
          v-if="isShowGuide"
          :group_roll="group_roll"
          :join_num="activity_data.join_num"
          @join="handleImmediatelyJoinGroup"
        />
        <!-- 组团流程 -->
        <groupFlow v-if="!isShowActivityOver" />
        <!-- 团队详情 -->
        <view v-if="isShowTeamDetail" class="team-detail-wrap">
          <teamDetail
            :group-rank="groupRank"
            :student_id="student_id"
            :isInGroup="isInGroup"
          />
          <view v-if="!fullGroup" class="team-detail-desc"
            >邀请好友领取更多花瓣～</view
          >
        </view>
        <!-- 活动已结束 -->
        <activityOver
          v-if="isShowActivityOver"
          :activity_status="activity_data.activity_status"
          @toIndexPageBefore="handleBeforeLeave"
        />
      </view>
    </scroll-view>
    <!-- 组团规则 -->
    <actionSheet :is-opened-modal.sync="isOpenedModal" :height="888">
      <view class="rule-modal">
        <view
          class="rule-modal-item"
          v-for="(item, index) in explainInfo"
          :key="item.id"
          >{{ index + 1 }}.{{ item.content }}</view
        >
      </view>
      <cloudTitle>组团规则</cloudTitle>
    </actionSheet>
    <!-- 编辑团名 -->
    <actionSheet
      :is-show-bottom-btn="true"
      :is-opened-modal.sync="isShowEditGroupNameModal"
      :height="554"
      class="edit-group-name-modal"
    >
      <editName
        :edit-modal-status="isShowEditGroupNameModal"
        :value="groupName"
        :group-info="groupInfo"
        :residue_edit_num="residue_edit_num"
        :rename="rename"
        @change="handleGetName"
        @showToast="handleSpecialNameShowToast"
      />
      <view slot="footer" class="edit-group-footer" @tap="handleEditGroup">
        <view data-type="cancel">暂不修改</view>
        <view data-type="ok">确认修改</view>
      </view>
      <cloudTitle>修改团队名称</cloudTitle>
    </actionSheet>
    <!-- toast提示 -->
    <at-toast
      :is-opened="is_opened"
      :text="toastText"
      :on-close="handleCloseToast"
    />
    <!-- 解散弹窗 -->
    <at-modal
      class="custom-confirm"
      :closeOnClickOverlay="false"
      :is-opened="isShowModal"
      :on-close="handleModalCancel"
      :on-cancel="handleModalCancel"
    >
      <AtModalContent
        >团队解散后将不再享受团队奖励，确定解散团队吗？</AtModalContent
      >
      <AtModalAction>
        <view class="modal-footer" @tap="handleModalOperate">
          <view data-key="dismiss">解散团队</view>
          <view data-key="no-dismiss">我再想想</view>
        </view>
      </AtModalAction>
    </at-modal>
    <!-- 移除团队成员的弹窗 -->
    <at-modal
      class="custom-confirm"
      :closeOnClickOverlay="false"
      :is-opened="isShowRemoveModal"
      :on-close="handleCancelRemove"
      :on-cancel="handleCancelRemove"
    >
      <AtModalContent>确定移出{{ removeUser.username }}吗？</AtModalContent>
      <AtModalAction>
        <view class="modal-footer" @tap="handleModalOperate">
          <view data-key="remove">狠心移出</view>
          <view data-key="no-remove">我再想想</view>
        </view>
      </AtModalAction>
    </at-modal>
    <!-- 退出团的弹窗 -->
    <at-modal
      class="custom-confirm"
      :closeOnClickOverlay="false"
      :is-opened="isShowOutGroupModal"
      :on-close="handleOutGroupCancel"
      :on-cancel="handleOutGroupCancel"
    >
      <AtModalContent
        >退团后将不再享受团队奖励，确定离开团队吗？</AtModalContent
      >
      <AtModalAction>
        <view class="modal-footer" @tap="handleModalOperate">
          <view data-key="leave">决定离开</view>
          <view data-key="no-leave">我再想想</view>
        </view>
      </AtModalAction>
    </at-modal>
    <!-- 成为团长 -->
    <AtCurtain :is-opened="isShowCurtainModal" :on-close="handleCloseCurtain">
      <view class="leader-modal">
        <view class="leader-modal-title">恭喜你，成为团长</view>
        <view class="leader-modal-desc">邀请好友入团，打卡领取更多奖励~</view>
        <view class="share">
          <view class="share-we">
            <label class="label-2-text" for="share">
              <image :lazy-load="true" class="share-logo" :src="wechatIcon" />
              <view>微信好友</view>
            </label>
            <button open-type="share" style="visibility: hidden;" id="share">
              分享
            </button>
          </view>
        </view>
        <image
          class="leader-modal-logo"
          :src="TEAM_LEADER_ICON"
          :lazy-load="true"
        />
      </view>
    </AtCurtain>

    <!-- 发放奖励弹窗 -->
    <AwardGive :show.sync="showAward" position="group_detail" />
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import actionSheet from "@/components/action-sheet/index";
import AwardGive from "@/components/award-give/index.vue";
import groupTips from "./components/group-tips";
import clockContent from "./clock-content";
import cloudTitle from "./components/cloud-container";
import activityOver from "./components/activity-over";
import teamDetail from "./components/team-detail";
import groupGuide from "./components/group-guide";
import editName from "./components/edit-group-name";
import operationMember from "./components/operation-member";
import { group_bg, group_rule_cloud } from "@/libs/image-url";
import globalData from "@/libs/globalData";
import { AtModalAction, AtModalContent, AtCurtain } from "taro-ui-vue";
import "./scss/index.scss";
import groupFlow from "./components/group-flow.vue";
import customHeader from "@/components/custom-header";
import {
  hasBackgroundBgTitleStyle,
  getInviteId,
  handleJudgeIsLogin,
  decodeQrcodeScene
} from "@/libs/util";
import {
  editGroupName,
  groupDetail,
  breakGroup,
  expelMember,
  exitGroup,
  explain,
  createGroup,
  joinGroup
} from "@/libs/api/group";
import {
  NORMAL,
  NOT_GROUP,
  FULL_GROUP,
  NOT_CITY,
  NOT_GRADE,
  NOT_ACTIVITY,
  OVER_ACTIVITY
} from "@/config/base-common";
/**微信图标 */
const wechatIcon =
  "http://xthk-edu-test.oss-cn-shenzhen.aliyuncs.com/1607501273291_0.8565171765556387";

/**成为团长的弹窗图标 */
const TEAM_LEADER_ICON =
  "http://xthk-edu-test.oss-cn-shenzhen.aliyuncs.com/1607501273291_0.45752527802595955";

/**展示活动已结束的状态容器 */
const overActivityStatusContainer = [
  NOT_CITY,
  NOT_GRADE,
  NOT_ACTIVITY,
  OVER_ACTIVITY
];
const OFFSET = 10; // 距离顶部便宜量
const GASBAG_TITLE_OFFSET = 20; // 顶部气囊按钮向下偏移量 总共标题的高 = 气囊的高度 + 距离顶部的位置 + 此偏移量

const NO_AVATAR_DEFAULT = require("@/assets/icon/no-avatar.png");
// 用户头像不足5个需要不足头像
const LEAST_AVATAR_NUM = 5;
/**策略集合 */
const Strategy = {};

/**重名错误状态码 */
const RENAME_CODE = 4001;

/**头像展示区最大展示头像数 */
const MAX_AVATAR_SIZE = 10;

/**组团规则图片 */
const GROUP_RULE =
  "http://xthk-edu-test.oss-cn-shenzhen.aliyuncs.com/1609150648868_0.424610088598649";

export default {
  components: {
    actionSheet,
    groupTips,
    clockContent,
    cloudTitle,
    activityOver,
    groupFlow,
    teamDetail,
    groupGuide,
    editName,
    operationMember,
    AtModalAction,
    AtModalContent,
    AtCurtain,
    customHeader,
    AwardGive
  },
  data() {
    return {
      TEAM_LEADER_ICON,
      wechatIcon,
      GROUP_RULE,
      showAward: false,
      navHeight: 0,
      scrollTop: 0,
      isOpenedModal: false,
      isShowEditGroupNameModal: false,
      groupName: "",
      rename: "",
      isRemoveStatus: false,
      isShowRemoveModal: false,
      isShowOutGroupModal: false,
      isShowCurtainModal: false,
      removeUser: {},
      groupRank: [],
      groupInfo: {}, //团信息
      activity_data: {}, // 活动信息
      activity_id: undefined, // 活动id
      group_roll: [], //滚动数据
      explainInfo: [],
      residue_edit_num: 0
    };
  },
  computed: {
    /**背景样式 */
    groupStyleBg() {
      return hasBackgroundBgTitleStyle(group_bg, 314, 584);
    },
    /**团id */
    group_id() {
      return this.groupInfo?.id;
    },
    /**是否展示活动已结束页面 */
    isShowActivityOver() {
      const status = this.activity_data?.activity_status;
      return overActivityStatusContainer.includes(status);
    },
    /**团成员是否人员 */
    hasGroupMember() {
      return this.groupInfo?.user_data?.some(i => !i.is_leader && !!i.username);
    },
    /**是否未成团 */
    isNotFormGroup() {
      return this.groupInfo?.status === NOT_GROUP;
    },
    /**是否在团中 */
    isInGroup() {
      return !!this.groupInfo.in_group;
    },
    /**是否展示立即入团模块 */
    isShowGuide() {
      return !this.isShowActivityOver && this.group_roll.length;
    },
    /**满团 */
    fullGroup() {
      return this.groupInfo.status === FULL_GROUP;
    },
    /**是否展示团队详情列表 */
    isShowTeamDetail() {
      // 1. 活动存在并有数据
      return !this.isShowActivityOver && this.groupRank?.length;
    },
    /**是否显示组团头部排行
     * 1. 无团成团时要隐藏 success_num
     */
    isShowHeadRank() {
      return this.activity_data?.success_num;
    },
    /**是否展示成员信息 */
    isshowMemberInfo() {
      // 1. 团有数据或者活动存在就会显示
      return !this.isShowActivityOver || this.group_id;
    },
    /**是否显示编辑团名按钮 */
    isShowEditButton() {
      return this.residue_edit_num > 0;
    },
    student_id() {
      return this.activity_data?.student_id || 0;
    },
    /**邀请弹窗相关 */
    inviteInfo() {
      const title = this.activity_data?.share_describe;
      // TODO:
      const imageUrl = this.activity_data?.share_img;
      return {
        title,
        imageUrl,
        path: `/pages/group/home/index?id=${this.activity_id}&invite_id=${this.student_id}`
      };
    },
    groupHomeContentStyle() {
      let style = !!this.groupInfo?.id ? {} : { "padding-top": "42rpx" };
      return style;
    }
  },
  onLoad({ id, invite_id, scene }) {
    console.log(scene, "scene");
    const sceneQuery = decodeQrcodeScene(scene);
    this.activity_id = sceneQuery?.id || id;
    invite_id = sceneQuery?.invite_id || invite_id;
    console.log(sceneQuery, "sceneQuery");
    if (invite_id) {
      Taro.setStorageSync("invite_id", invite_id);
      Taro.setStorageSync("login_invite_id", invite_id);
    }
  },
  onShow() {
    this.showAward = true;
    this.handleGetGroupDetail();
    console.log(Taro.getCurrentPages());
  },
  onShareAppMessage({ from }) {
    if (from === "button") {
      this.isShowCurtainModal = false;
      // 来自页面内转发按钮
      return {
        ...this.inviteInfo
      };
    }
  },
  methods: {
    /**如果是被邀请人，离开此页面会清除掉邀请id */
    handleBeforeLeave() {
      getInviteId() && Taro.removeStorageSync("invite_id");
    },
    /**跳转排行榜 */
    handleLookRank() {
      this.handleBeforeLeave();
      Taro.navigateTo({
        url: `/pages/group-ranking/index?activity_id=${this.activity_id}`
      });
    },
    /**获取组团规则说明 */
    async handleGetExplain() {
      const { data } = await explain();
      this.explainInfo = data;
    },
    /**打卡操作 */
    handlePunchOperate(type) {
      /**打卡 */
      Strategy["punch"] = () => {
        this.handleBeforeLeave();
        Taro.navigateTo({
          url: `/pages/activity-detail/index?id=${this.activity_id}`,
          complete: () => {
            this.isLoading = false;
          }
        });
      };
      /**立即入团 */
      Strategy["in-group"] = this.handleImmediatelyJoinGroup.bind(
        this,
        this.group_id,
        true
      );
      /**邀请好友 */
      Strategy["invite"] = () => {
        this.isLoading = false;
        this.handleBeforeLeave();
        Taro.navigateTo({
          url: `/pages/group/invitation/index?id=${this.activity_id}`
        });
      };
      /**当团长 */
      Strategy["team-leader"] = () => {
        this.handleCreateGroup();
      };
      Strategy[type] && Strategy[type]();
    },
    /**我要当团长 开团 */
    async handleCreateGroup() {
      if (this.isLoading) return;
      this.isLoading = true;
      const hasAuth = handleJudgeIsLogin();
      if (!hasAuth) return;
      const [err] = await this.$captureCatch(
        createGroup({ activity_id: this.activity_id })
      );
      if (err) {
        this.isLoading = false;
        this.$message(err?.message);
        return;
      }
      // TODO:当团长的弹窗
      await this.handleGetGroupDetail();
      this.showAward = true;
      this.isShowCurtainModal = true;
    },
    /**toast消息提示 */
    handleToast(message) {
      this.toastText = message;
      this.is_opened = true;
      this.isLoading = false;
    },
    /**移除已入团的成员 */
    handleRemoveMember(user) {
      this.removeUser = user;
      this.isShowRemoveModal = true;
    },
    /**解散团队确定 */
    async handleDismissOk() {
      if (this.isLoading || !this.group_id) return;
      this.isLoading = true;
      const [err, data] = await this.$captureCatch(
        breakGroup({ id: this.group_id })
      );
      this.handleModalCancel();
      if (err) {
        this.isLoading = false;
        this.$message(err.message);
        return;
      }
      await this.handleGetGroupDetail();
      this.$message("团已解散");
    },
    /**移除成员确定 */
    async handleRemoveMemberOk() {
      if (this.isLoading || !this.group_id) return;
      this.isLoading = true;
      const [err, data] = await this.$captureCatch(
        expelMember({ id: this.group_id, student_id: this.removeUser.id })
      );
      this.handleCancelRemove();
      if (err) {
        this.isLoading = false;
        this.$message(err.message);
        return;
      }
      await this.handleGetGroupDetail();
      this.$message("移除成功");
      this.isRemoveStatus = false;
    },
    /**退出团 决定离开 */
    async handleDecisionLeave() {
      if (this.isLoading || !this.group_id) return;
      this.isLoading = true;
      const [err, data] = await this.$captureCatch(
        exitGroup({ id: this.group_id })
      );
      this.isShowOutGroupModal = false;
      if (err) {
        this.isLoading = false;
        this.$message(err.message);
        return;
      }
      await this.handleGetGroupDetail();
      this.$message("退团成功");
    },
    /**立即入团 */
    async handleImmediatelyJoinGroup(
      id,
      isTakeInvite = false /**是否带上邀请人id,组团区才会带上此邀请id */
    ) {
      const hasAuth = handleJudgeIsLogin();
      if (!hasAuth) return;

      if (this.isLoading) return;
      this.isLoading = true;
      let invite_user_id = undefined;
      if (isTakeInvite) invite_user_id = getInviteId();
      const [err, { data }] = await this.$captureCatch(
        joinGroup({ id, invite_user_id })
      );
      this.isLoading = false;
      if (err) {
        this.$message(err?.message);
        /**加入团，团长又解散该团 */
        if (err?.status_code === 4002) {
          this.handleGetGroupDetail();
        }
        return;
      }
      invite_user_id && Taro.removeStorageSync("invite_id");
      this.showAward = true;
      await this.handleGetGroupDetail();
      this.$message("入团成功，快去邀请好友吧");
      this.isLoading = false;
    },
    /**解散团队 移除成员弹窗操作 */
    handleModalOperate({ target: { dataset } }) {
      const { key: type } = dataset;
      if (!type) return;
      let strategy = {};
      /**解散团队 */
      strategy["dismiss"] = this.handleDismissOk;
      strategy["no-dismiss"] = this.handleModalCancel;
      /**移除团队成员 */
      strategy["remove"] = this.handleRemoveMemberOk;
      strategy["no-remove"] = this.handleCancelRemove;
      /**决定离开 */
      strategy["leave"] = this.handleDecisionLeave;
      strategy["no-leave"] = this.handleOutGroupCancel;
      strategy[type] && strategy[type]();
    },
    /**团成员操作  */
    handleOperate(type) {
      Strategy["dismiss"] = () => {
        this.isShowModal = true;
      };
      /**退出团 */

      Strategy["out-group"] = () => {
        this.isShowOutGroupModal = true;
      };
      /**移除 */

      Strategy["remove-member"] = () => {
        this.isRemoveStatus = !this.isRemoveStatus;
      };

      Strategy[type] && Strategy[type]();
    },
    /**获取团详情 */
    async handleGetGroupDetail() {
      const query = { activity_id: this.activity_id, invite_id: getInviteId() };
      this.$startLoading();
      const [err, { data }] = await this.$captureCatch(groupDetail(query));
      this.isLoading = false;
      this.$endLoading();
      if (err) return this.$message(err.message);
      /**团队详情列表 */
      this.groupRank = Object.freeze(data?.group_rank || []);
      /**活动信息 */

      this.activity_data = Object.freeze(data?.activity_data || {});
      /**团信息 */
      this.groupInfo = data?.group_info || {};
      /**如果用户没用达到5个，需要添加默认头像 */
      this.handleInitUser();
      /**可编辑次数 */
      this.residue_edit_num = this.groupInfo?.edit_num || 0;

      this.groupName = (data?.group_info?.group_name || "").slice(0, 10);
      /**滚动数据 */
      this.group_roll = Object.freeze(data?.group_roll || []);
    },
    /**初始化用户头像数据 */
    handleInitUser() {
      const {
        user_data = [],
        lack_success_num = 0,
        lack_full_num = 0,
        max_num = 0
      } = this.groupInfo;
      if (!user_data.length) return;
      /**现有人员数 */
      const teamUserNum = user_data?.length;
      /**成团或满团人数的最大数 */
      const fullGroupNum =
        teamUserNum + Math.max(lack_full_num, lack_success_num);
      /**
       * 如果团状态没有满团，并且都不超过最大展示限制数10，则需要格式化
       */
      /**总共数目超过最大限制不替补头像 */
      if (teamUserNum >= MAX_AVATAR_SIZE) return;

      let fillNum = Math.min(fullGroupNum, MAX_AVATAR_SIZE);

      let minAvatarNum =
        teamUserNum < LEAST_AVATAR_NUM ? LEAST_AVATAR_NUM : fillNum;
      // 若满团人数≤5，则按实际满团人数展示组团空位
      if (max_num <= LEAST_AVATAR_NUM) minAvatarNum = max_num;

      // 若5＜满团人数≤10 则默认展示5个组团空位，当5个空位填满时（即当前团成员数=5时），
      // 再按实际剩余数（满团人数-5）展示剩余空位，最多展示10个人，
      if (LEAST_AVATAR_NUM < max_num && max_num <= MAX_AVATAR_SIZE) {
        // 1.默认5个空位未填满时
        if (teamUserNum < LEAST_AVATAR_NUM) minAvatarNum = LEAST_AVATAR_NUM;
        else minAvatarNum = Math.max(LEAST_AVATAR_NUM, fillNum);
      }

      /**替补空位的逻辑 */
      if (teamUserNum < minAvatarNum) {
        const offset = minAvatarNum - teamUserNum;
        let fullUser = [];
        for (let i = 0; i < offset; i++) {
          fullUser.push({
            avatar: NO_AVATAR_DEFAULT,
            id: i - MAX_AVATAR_SIZE, // 防止id重复
            username: undefined
          });
        }
        this.groupInfo.user_data = [...user_data, ...fullUser];
      }
    },
    /**编辑团名操作 */
    async handleEditGroup({
      target: {
        dataset: { type }
      }
    }) {
      if (!type || this.isLoading) return;
      if (type === "cancel") {
        this.isShowEditGroupNameModal = false;
        return;
      }
      this.isLoading = true;
      const [
        err,
        { data: { residue_edit_num = 0 } = {} }
      ] = await this.$captureCatch(
        editGroupName({
          id: this.group_id,
          group_name: this.groupName
        })
      );
      this.isLoading = false;
      if (err) {
        this.$message(err?.message);
        if (err?.status_code === RENAME_CODE) {
          this.rename = err?.message;
          return;
        }
        this.isShowEditGroupNameModal = false;
        return;
      }

      this.$message("修改成功");
      this.isLoading = false;
      this.isShowEditGroupNameModal = false;
      this.residue_edit_num = residue_edit_num;
      this.groupInfo.group_name = this.groupName;
    },
    /**获取组团名 */
    handleGetName(name) {
      this.groupName = name;
      this.rename = "";
    },
    /**编辑团名 */
    handleEditGroupName() {
      // TODO:重置团名
      // this.groupName = "";
      this.rename = "";
      this.isShowEditGroupNameModal = true;
    },
    /**团名特殊字符提示 */
    handleSpecialNameShowToast(text) {
      this.toastText = text;
      this.is_opened = true;
    },
    handleScroll({ target: { scrollTop } }) {
      this.scrollTop = scrollTop;
    },
    /**展示规则弹窗 */
    handleShowRuleModal() {
      !this.explainInfo?.length && this.handleGetExplain();
      this.isOpenedModal = true;
    },
    /**关闭移除成员弹窗 */
    handleCancelRemove() {
      this.isShowRemoveModal = false;
    },
    /**退出团的弹窗 */
    handleOutGroupCancel() {
      this.isShowOutGroupModal = false;
    },
    handleCloseCurtain() {
      this.isShowCurtainModal = false;
    }
  }
};
</script>
